package com.lanyam.travel.base.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lanyam.travel.base.dao.LineGoodsMapper;
import com.lanyam.travel.base.dao.TravelLineMapper;
import com.lanyam.travel.base.entity.GoodsDate;
import com.lanyam.travel.base.entity.GoodsInfo;
import com.lanyam.travel.base.entity.HomeProduct;
import com.lanyam.travel.base.entity.Product;
import com.lanyam.travel.base.entity.ScenicHotel;
import com.lanyam.travel.base.entity.SupplierInfo;
import com.lanyam.travel.base.entity.TravelLine;
import com.lanyam.travel.base.entity.vo.TravelLineVo;
import com.lanyam.travel.base.service.IGoodsDateService;
import com.lanyam.travel.base.service.ILineGoodsService;
import com.lanyam.travel.base.service.ISupplierInfoService;
import com.lanyam.travel.base.service.ITravelLineService;

@Service
public class TravelLineServiceImpl implements ITravelLineService {

    @Autowired
    private TravelLineMapper travelLineMapper;

    @Autowired
    private IGoodsDateService goodsDateService;
    
    @Autowired
	private ISupplierInfoService supplierInfoService;

    @Override
    public List<TravelLine> getAllTravelLine() {
        // TODO Auto-generated method stub
        List<TravelLine> allTravelLine = travelLineMapper.selectList(null);
        return allTravelLine;
    }

    @Override
    public void deleteById(String productId) {
        // TODO Auto-generated method stub
        travelLineMapper.deleteById(productId);
    }

    @Override
    public void update(TravelLine travelLine) {
        // TODO Auto-generated method stub
    	TravelLine originLine = getTravelLineById(travelLine.getId());
    	if(originLine.getPrice().doubleValue()!=travelLine.getPrice().doubleValue())
    	{
    		Calendar calendar = Calendar.getInstance();
    		calendar.set(Calendar.HOUR_OF_DAY, 0);
    		calendar.set(Calendar.MINUTE, 0);
    		calendar.set(Calendar.SECOND, 0);
    		List<GoodsDate> GoodsDateInMouth = goodsDateService.queryGoodsDateInMouth(travelLine.getId(), calendar.getTime());
    		for (GoodsDate goodsDate : GoodsDateInMouth) {
    			goodsDate.setPrice(travelLine.getPrice());
    			goodsDateService.updateGoodsDate(goodsDate);
			}
    	}
        travelLineMapper.updateById(travelLine);
    }

    /**
     * region:区分国内游/国际游，值=0代表国内，1代表国外
     * price:价格排序，值=0代表升序排列（默认），1代表降序排列
     * distance:距离排序，值=0代表升序排列（默认），1代表降序排列
     * location:地区搜索
     * star:星级搜索
     * commentScore:评分排序，值=0代表升序排列，1代表降序排列（默认）
     */
    @Override
    public Page<TravelLine> queryTravelLineList(int pageNum, int pageSize, Map<String, Object> reqMap) {
        // TODO Auto-generated method stub
        QueryWrapper<TravelLine> queryWrapper = new QueryWrapper<TravelLine>();
        queryWrapper.eq("status", 1);
    	String region = reqMap.get("region").toString();
        String location = reqMap.get("location")!=null ? reqMap.get("location").toString():"";
        String sortByPrice = reqMap.get("price").toString();
        String star = reqMap.get("star")!=null ? reqMap.get("star").toString():"";
        String sortByCommentScore = reqMap.get("commentScore")!=null ? reqMap.get("commentScore").toString():"";
        if (!StringUtils.isEmpty(region)) {
            queryWrapper.eq("region", region);
        }
        if (!StringUtils.isEmpty(star)) {
            queryWrapper.eq("star", star);
        }
        if (!StringUtils.isEmpty(location)) {
            queryWrapper.like("location", location);
        }
        if (!StringUtils.isEmpty(sortByPrice)) {
            if ("0".equals(sortByPrice)) {
                queryWrapper.orderByAsc("price");
            } else {
                queryWrapper.orderByDesc("price");
            }
        }
        if (!StringUtils.isEmpty(sortByCommentScore)) {
            if ("0".equals(sortByCommentScore)) {
                queryWrapper.orderByAsc("comment_score");
            } else {
                queryWrapper.orderByDesc("comment_score");
            }
        }
        Page<TravelLine> page = new Page<TravelLine>(pageNum, pageSize);
        Page<TravelLine> ipage = travelLineMapper.selectPage(page, queryWrapper);
        List<TravelLine> lines = ipage.getRecords();
//		for (TravelLine travelLine : lines) {
//			//这里有性能问题，可以优化
//			List<ScenicHotel> secnicOnLine = lineGoodsService.queryGoodsOnLine(travelLine.getId());
//			travelLine.setScenicList(secnicOnLine);
//		}
        return ipage;
    }

    @Override
    public List<TravelLine> getTravelLineByMap(Map<String, Object> reqMap) {
        // TODO Auto-generated method stub
    	String name = (String) reqMap.get("name");
    	QueryWrapper<TravelLine> wrapper = new QueryWrapper<TravelLine>();
    	wrapper.like("name", name);
    	
        return travelLineMapper.selectList(wrapper);
    }

    @Override
    public TravelLine queryTravelLineById(String id) {
        // TODO Auto-generated method stub
        return travelLineMapper.selectById(id);
    }

    @Override
    public List<TravelLine> batchQueryTravelLines(List<String> lineIds) {
        // TODO Auto-generated method stub
        return travelLineMapper.selectBatchIds(lineIds);
    }

    @Override
    public void addTraveLine(TravelLine travelLine) {
        // TODO Auto-generated method stub
        travelLineMapper.insert(travelLine);
    }

    @Override
    public TravelLine getTravelLineById(String lineId) {
        // TODO Auto-generated method stub
        return travelLineMapper.selectById(lineId);
    }

    @Override
    public TravelLine queryTravelLineInfo(String lineId) {
        // TODO Auto-generated method stub
        TravelLine line = getTravelLineById(lineId);
        
        return line;
    }

    @Override
    public Page<TravelLine> queryTravelLinePage(int pageNum, int pageSize, Map<String, String> reqMap) {
        // TODO Auto-generated method stub
        QueryWrapper<TravelLine> queryWrapper = new QueryWrapper<TravelLine>();
        if (null == reqMap) {
            queryWrapper = null;
        } else {
            String name = reqMap.get("name");
            if (!StringUtils.isEmpty(name)) {
                queryWrapper.like("NAME", name);
            }
            
            String region = reqMap.get("region");
            if (!StringUtils.isEmpty(region)) {
                queryWrapper.eq("region", region);
            }
            String status = reqMap.get("status");
			if(!StringUtils.isEmpty(status))
			{
				queryWrapper.eq("status", status);
			}
            String startLocation = reqMap.get("startLocation");
            if (!StringUtils.isEmpty(startLocation)) {
                queryWrapper.like("start_location", startLocation);
            }
            String endLocation = reqMap.get("endLocation");
            if (!StringUtils.isEmpty(endLocation)) {
                queryWrapper.like("end_location", endLocation);
            }
            String productType = reqMap.get("productType");
            if (!StringUtils.isEmpty(productType)) {
                queryWrapper.eq("productType", productType);
            }
            String star= reqMap.get("star");
            if (!StringUtils.isEmpty(star)) {
                queryWrapper.eq("star", star);
            }
            String days = reqMap.get("days");
            if (!StringUtils.isEmpty(days)) {
                queryWrapper.eq("days", days);
            }
            String lowPrice = reqMap.get("lowPrice");
			String highPrice = reqMap.get("highPrice");
			if(!StringUtils.isEmpty(lowPrice) && !StringUtils.isEmpty(highPrice))
			{
				queryWrapper.between("price", lowPrice,highPrice);
			}
			else if(!StringUtils.isEmpty(lowPrice) && StringUtils.isEmpty(highPrice))
			{
				queryWrapper.ge("price", lowPrice);
			}
			else if(StringUtils.isEmpty(lowPrice) && !StringUtils.isEmpty(highPrice))
			{
				queryWrapper.lt("price", highPrice);
			}
			try {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
				String createTime = reqMap.get("createTime");
				Date startDate = null;
				if(!StringUtils.isEmpty(createTime))
				{
					startDate = sdf.parse(createTime);
					queryWrapper.eq("create_time", startDate);
				}
				
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

        }
        Page<TravelLine> page = new Page<TravelLine>(pageNum, pageSize);
        Page<TravelLine> ipage = travelLineMapper.selectPage(page, queryWrapper);
        List<SupplierInfo> allSupplier = supplierInfoService.getAllSupplier();
		Map<String,SupplierInfo> supplierMap = new HashMap<String, SupplierInfo>();
		for (SupplierInfo supplierInfo : allSupplier) {
			supplierMap.put(supplierInfo.getId(), supplierInfo);
		}
		List<TravelLine> lineList = ipage.getRecords();
		SupplierInfo info;
		for (TravelLine line : lineList) {
			info = supplierMap.get(line.getSupplyId());
			if(null != info)
			{
				line.setSupplierName(info.getSupplierName());
			}
		}
        return ipage;
    }

    @Override
    public List<? extends Product> selectList(QueryWrapper<TravelLine> lineWrapper) {
        // TODO Auto-generated method stub
        List<TravelLine> selectList = travelLineMapper.selectList(lineWrapper);
        return selectList;
    }

	@Override
	public List<TravelLine> searchByKey(String key) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<TravelLine> getProductBySupplier(String supplierId) {
		// TODO Auto-generated method stub
		QueryWrapper<TravelLine> wrapper = new QueryWrapper<TravelLine>();
		wrapper.eq("supply_id", supplierId);
		List<TravelLine> lineList = travelLineMapper.selectList(wrapper);
		return lineList;
	}

}
